package org.jdcenter.rmi.impl;

import java.rmi.*;
import java.net.MalformedURLException;

import org.jdcenter.rmi.abs.*;

public class RemoteChannel implements RpcChannel {
    private String url;
    private RpcChannel channel;

    public RemoteChannel(String url) throws URLException, RemoteException {
        this.url = url;
        this.renew();
    }

    public synchronized void renew() throws URLException, RemoteException {
        try {
            this.channel = (RpcChannel) Naming.lookup(url);
        } catch (MalformedURLException e) {
            throw new URLException(e);
        } catch (NotBoundException e) {
            throw new URLException(e);
        }
    }

    public void close() {
        this.channel = null;
    }

    public String getUrl() {
        return url;
    }

    private boolean renew_i() {
        try {
            renew();
            return true;
        } catch (RemoteException e) {
        } catch (URLException e) {
        }

        return false;
    }

    public int advise(RpcHandler handler, int cookie) throws RemoteException, HandlerResumeException {
        return this.channel.advise(handler, cookie);
    }
    
    public Object lookup()throws RemoteException{
    	return this.channel.lookup();
    }

    public void unadvise(int cookie) throws RemoteException {
        this.channel.unadvise(cookie);
    }

    public void tick() throws RemoteException {
        try {
            this.channel.tick();
        } catch(RemoteException e) {
            if(!renew_i())
                throw e;
            this.channel.tick();
        }
    }

    public Object invoke(int cookie,String method,Object[] args)
                throws RemoteException, HandlerException, HandlerInvalidException, HandlerRejectedException {
        try {
            return this.channel.invoke(cookie,method,args);
        } catch(RemoteException e) {
            if(renew_i())
                return channel.invoke(cookie,method,args);
            throw e;
        }
    }
}

